import {WeaForm, WeaTableNew, WeaSwitch} from 'comsMobx';
import {observable, action, toJS} from 'mobx';
import {inject, observer} from 'mobx-react';
import React from 'react';
import {WeaNewScroll, WeaTools, WeaDialog, WeaFormItem, WeaSearchGroup, WeaRightMenu, WeaLocaleProvider, WeaHelpfulTip} from 'ecCom';
import {Button, Row, Col, Modal} from 'antd';
import IntegrationForm_Table from "./IntegrationForm_Table";
import {NodesTable} from "./IntegrationForm_Nodes";
import * as conLockApi from "../apis/contractLockSend";

const getLabel = WeaLocaleProvider.getLabel;

@inject("myCreateForm")
@observer
class IntegrationForm extends React.Component {
    constructor(props) {
        super(props);
    }

    /**
     * 表单数据发生变化，触发的事件
     * @param data
     */
    onChange = (data) => {
        const { selectedKey} = this.props;
        if(selectedKey == 1) {
            this.fnIntegrationOnChange(data);
        }
        if (selectedKey == 0) {
            this.fnServerOnChange(data);
        }
        if (selectedKey == 2) {
            this.fnPhysicalSealOnChange(data);
        }
    }

    /**
     * 物理用印集成配置发生改变事件
     * @param data
     */
    fnPhysicalSealOnChange = (data) => {
        const {myCreateForm} = this.props;
        if (data.workflowid) {//物理用印选择改变了流程
            let wfid = data.workflowid.value;
            if (wfid) {
                this.fnCheckWorkflowidIsUsed(wfid);
            } else {
                this.fnChangeEnd(myCreateForm, "");
            }
        }
    }

    /**
     * 契约锁集成改变事件
     */
    fnIntegrationOnChange = (data) => {
        const {myCreateForm} = this.props;
        //针对 合同模板字段，与合同文件字段二选一的操作  [公有不存在这个问题]
        if ((data.templateField || data.documentField)) {//只要选了一个另一个就不用必填了
            const {alldatas, conditioninfo, setConditioninfo, ispublics = true} = myCreateForm;
            const {form} = alldatas;
            let tem = {value: form.getFormDatas().templateField && form.getFormDatas().templateField.value},
                doc = {value: form.getFormDatas().documentField && form.getFormDatas().documentField.value};
            if (ispublics) {//公有合同文件字段必填
                tem = {rules: false, viewAttr: "2", ...doc}
                doc = {rules: "required", viewAttr: "3", ...tem}
            } else {
                if (doc.value || tem.value) {//说明二选一了
                    doc = {rules: false, viewAttr: "2", ...doc}
                    tem = {rules: false, viewAttr: "2", ...tem}
                } else {//数据被清空
                    doc = {rules: "required", viewAttr: "3", ...doc}
                    tem = {rules: "required", viewAttr: "3", ...tem}
                }
            }
            conditioninfo && conditioninfo.map(item => {
                if (item.type == "contractmsg") {//合同信息
                    item.items && item.items.map(items => {
                        if (items.domkey == "templateField") {
                            // tem.rules ? items.rules = tem.rules : delete  items.rules;
                            items.viewAttr = tem.viewAttr;
                            items.rules = tem.rules;
                        }
                        if (items.domkey == "documentField") {
                            items.viewAttr = doc.viewAttr;
                            items.rules = doc.rules;
                        }
                    })
                }
            });
            alldatas.form = new WeaForm();
            alldatas.form.initFormFields(toJS(conditioninfo));
            alldatas.form.setCondition(toJS(conditioninfo));
            alldatas.form.updateFields(form.getFormDatas())
        }

        if(true) {
        const {alldatas, conditioninfo, setConditioninfo, ispublics = true} = myCreateForm;
        const {form} = alldatas;

            let key =  form.getFormParams().serverId;
            let itemdata =  form.getField("serverId");
            let _ispublic = true;
            key && itemdata && itemdata.options && itemdata.options.map( item => {//获得所有下拉选遍历查看数据
                if(item && item.key == key && item.otherparams) {//是当前的配置
                //得到当前服务类型 --在otherparams参数中
                let type = item.otherparams.servertype || "0";
                if(type == "0") {//公有
                    _ispublic = true;
                } else if(type == "1") {//私有
                    _ispublic = false;
                }
            }
        });

        let tem = {value: form.getFormDatas().templateField && form.getFormDatas().templateField.value};
        let cat = {value: (form.getFormDatas().isCreateByCategory && form.getFormDatas().isCreateByCategory.value) || _ispublic };
        let down = {value: form.getFormDatas().downloadField && form.getFormDatas().downloadField.value};
        let downsc = {value: form.getFormDatas().downloadSecCategory && form.getFormDatas().downloadSecCategory.value};

        console.log(form.getFormDatas());

        if ((tem.value || cat.value == "1") && down.value ) {//下载目录必填
            downsc = {rules: "required" , viewAttr: "3", ...downsc}
        }

        conditioninfo && conditioninfo.map(item => {
            if (item.type == "contractmsg") {//合同信息
            item.items && item.items.map(items => {
                if (items.domkey == "downloadSecCategory") {
                items.viewAttr = downsc.viewAttr;
                items.rules = downsc.rules;
            }

        })
        }
    });
        alldatas.form = new WeaForm();
        alldatas.form.initFormFields(toJS(conditioninfo));
        alldatas.form.setCondition(toJS(conditioninfo));
        alldatas.form.updateFields(form.getFormDatas())
    }

        if (data.workflowid) {//集成登录改变了流程
            let wfid = data.workflowid.value;
            if (wfid) {//查看流程在是否已配置了
                this.fnCheckWorkflowidIsUsed(wfid);
            } else {
                this.fnChangeEnd(myCreateForm, "")
            }
        }

        if (data.serverId && data.serverId.value) {//契约锁服务,且存在值
            const {conditioninfo, alldatas} = myCreateForm;
            const {form} = alldatas;
            let key =  form.getFormParams().serverId;
            let itemdata =  form.getField("serverId");
            let _ispublic = true;
            key && itemdata && itemdata.options && itemdata.options.map( item => {//获得所有下拉选遍历查看数据
                if(item && item.key == key && item.otherparams) {//是当前的配置
                    //得到当前服务类型 --在otherparams参数中
                    let type = item.otherparams.servertype || "0";
                    if(type == "0") {//公有
                        _ispublic = true;
                    } else if(type == "1") {//私有
                        _ispublic = false;
                    }
                }
            });
            let tem = {value: form.getFormDatas().templateField && form.getFormDatas().templateField.value};
            let doc = {value: form.getFormDatas().documentField && form.getFormDatas().documentField.value};
            let cat = {value: (form.getFormDatas().isCreateByCategory && form.getFormDatas().isCreateByCategory.value) || _ispublic };
            let down = {value: form.getFormDatas().downloadField && form.getFormDatas().downloadField.value};
            let downsc = {value: form.getFormDatas().downloadSecCategory && form.getFormDatas().downloadSecCategory.value};
            myCreateForm.setIspublics(_ispublic);
            if (!tem.value && !doc.value) {//两者都为空时，设置显示必填项
                doc = {rules: "required", viewAttr: "3", ...doc}
                tem = {rules: "required", viewAttr: "3", ...tem}
            }
            if ((tem.value || cat.value == "1") && down.value ) {//下载目录必填
                downsc = {rules: "required" , viewAttr: "3", ...downsc}
            }
            conditioninfo && conditioninfo.map(item => {
                if (item.type == "contractmsg") {//合同信息
                    item.items && item.items.map(items => {
                        if (items.domkey == "templateField") {
                            items.viewAttr = tem.viewAttr;
                            items.rules = tem.rules;
                        }
                        if (items.domkey == "documentField") {
                            items.viewAttr = doc.viewAttr;
                            items.rules = doc.rules;
                        }
                        if(items.domkey == "downloadSecCategory") {
                            items.viewAttr = downsc.viewAttr;
                            items.rules = downsc.rules;
                        }
                    })
                }
            })
            alldatas.form = new WeaForm();
            alldatas.form.initFormFields(toJS(conditioninfo));
            alldatas.form.setCondition(toJS(conditioninfo));
            alldatas.form.updateFields(form.getFormDatas())
        }
    }

    /**
     * 检查当前选择的流程是否已配置
     */
    fnCheckWorkflowidIsUsed = (wfid) => {
        const {toptab, selectedKey, myCreateForm} = this.props;
        let groupid = "";
        if(selectedKey && toptab[selectedKey] && toptab[selectedKey].groupid) {
            groupid = toptab[selectedKey].groupid;
        }
        myCreateForm.doCheckWorkflowidIsUsed(wfid, groupid, this.fnChangeEnd)
    }

    /**
     * 契约锁服务改变事件
     */
    fnServerOnChange = (data) => {
        const {myCreateForm} = this.props;
        const {alldatas, conditioninfo, setConditioninfo, ispublics = true} = myCreateForm;
        const {form} = alldatas;
        let inte = {value: myCreateForm.alldatas.form.getFormDatas().integratedLoginId && myCreateForm.alldatas.form.getFormDatas().integratedLoginId.value},
            qysl = {value: myCreateForm.alldatas.form.getFormDatas().isqyslogin && myCreateForm.alldatas.form.getFormDatas().isqyslogin.value};
        if (data.serverType) {//契约锁服务选择服务类型需要处理的事件、
            let helpfulTip_serverUrl = "";
            let helpfulTip_access = "";
            if (data.serverType.value == 1) {//私有  集成登录标识，与使用契约锁统一认证  需要二选一
                myCreateForm.setIspublics(false);
                helpfulTip_serverUrl = getLabel(509438, "请填入契约锁私有化系统的API服务地址");
                helpfulTip_access = getLabel(509440, "请登陆契约锁控制台-集成中心-集成配置中获取");
            } else {//公有
                myCreateForm.setIspublics(true);
                helpfulTip_serverUrl = getLabel(509437, "请填入契约锁公有云系统的API服务地址");
                helpfulTip_access = getLabel(509439, "请登陆契约锁开放平台-配置-开发设置中获取");
                qysl = {rules: false, viewAttr: "2", ...qysl};
                inte = {rules: "required", viewAttr: "3", ...inte}
            }
            conditioninfo && conditioninfo.map(item => {
                item.items && item.items.map(items => {
                    if ("serverUrl" === items.domkey[0]) {
                        items.helpfulTip = helpfulTip_serverUrl;
                    } else if ("accessKey" === items.domkey[0] || "accessSecret" === items.domkey[0]) {
                        items.helpfulTip = helpfulTip_access;
                    }
                    if (items.domkey[0] === "integratedLoginId") {
                        items.viewAttr = inte.viewAttr;
                        items.rules = inte.rules;
                    }
                    if (items.domkey[0] === "isqyslogin") {
                        items.viewAttr = qysl.viewAttr;
                        items.rules = qysl.rules;
                    }
                })
            })
        }

        if ((data.integratedLoginId || data.isqyslogin)) {//只要选了一个另一个就不用必填了
            if (ispublics) {//公有合同文件字段必填
                inte = {rules: "required", viewAttr: "3", ...inte}
                qysl = {rules: false, viewAttr: "2", ...qysl}
            } else {
                inte = {rules: false, viewAttr: "2", ...inte}
            }
            conditioninfo && conditioninfo.map(item => {
                item.items && item.items.map(items => {
                    if (items.domkey == "integratedLoginId") {
                        // tem.rules ? items.rules = tem.rules : delete  items.rules;
                        items.viewAttr = inte.viewAttr;
                        items.rules = inte.rules;
                    }
                    if (items.domkey == "isqyslogin") {
                        items.viewAttr = qysl.viewAttr;
                        items.rules = qysl.rules;
                    }
                })
            });
        }
        alldatas.form = new WeaForm();
        alldatas.form.initFormFields(toJS(conditioninfo));
        alldatas.form.setCondition(toJS(conditioninfo));
        alldatas.form.updateFields(form.getFormDatas())
    }

    /**
     * 改变数据状态，特别是用来进行动态修改浏览按钮的关键id
     * @param myCreateForm
     * @param wfid
     */
    fnChangeEnd = (myCreateForm, wfid = "") => {
        myCreateForm.setWorkflowid(wfid);
        let wfparams = {workflowid:myCreateForm.alldatas.form.getFormDatas().workflowid};//得到流程相关参数
        myCreateForm.alldatas.form && myCreateForm.alldatas.form.getFormDatas() &&
        myCreateForm.alldatas.form.getFormDatas().serverId && (wfparams["serverId"]= myCreateForm.alldatas.form.getFormDatas().serverId)
        // myCreateForm.alldatas.form.resetForm();//重置表单
        myCreateForm.alldatas.form.updateFields(wfparams);//设置不变参数流程相关
        this.setCompleteURL(wfid);
        //判断是否是选中了流程，如果没有选中清空明细
        if(wfid==""){
            let conditioninfo = myCreateForm.conditioninfo;
            let conditionold = [];//存储最原始的condition值
            for(var i =0;i<5;i++){
                conditionold.push(conditioninfo[4].items[i]);
            }
            conditioninfo[4].items = conditionold;
        }
    }

    /**
     * 选择流程后给每一个浏览按钮添加流程id
     * */
    setCompleteURL = wfid => {
        const {myCreateForm} = this.props;
        const {alldatas, conditioninfo, setConditioninfo} = myCreateForm;
        const {form} = alldatas;
        let condition = toJS(conditioninfo);
        condition && toJS(condition).map(item => {
            item && item.items && item.items.map(field => {
                if (field.domkey.includes("serverSource")) {//特殊处理--契约锁服务表单字段
                    field.selectLinkageDatas && field.selectLinkageDatas[1] &&
                    field.selectLinkageDatas[1].browserConditionParam &&
                    this.fnSetBrowWorkflow(field.selectLinkageDatas[1].browserConditionParam, wfid);
                } else {
                    field.browserConditionParam && field.otherParams && field.otherParams.isAssociationWF && this.fnSetBrowWorkflow(field.browserConditionParam, wfid)
                }
            })
        })
        setConditioninfo(condition)
    }

    /**
     * 动态修改浏览按钮参数方法
     * @param browserConditionParam
     * @param workflowid
     * @returns {*}
     */
    fnSetBrowWorkflow = (browserConditionParam, workflowid) => {
        if (browserConditionParam && browserConditionParam.conditionDataParams) {
            browserConditionParam.conditionDataParams.workflowId = workflowid;
            browserConditionParam.conditionDataParams.workflowid = workflowid;
        }
        if (browserConditionParam && browserConditionParam.completeParams) {
            browserConditionParam.completeParams.workflowId = workflowid;
            browserConditionParam.completeParams.workflowid = workflowid;
        }
        if (browserConditionParam && browserConditionParam.destDataParams) {
            browserConditionParam.destDataParams.workflowId = workflowid;
            browserConditionParam.destDataParams.workflowid = workflowid;
        }
        if (browserConditionParam && browserConditionParam.dataParams) {
            browserConditionParam.dataParams.workflowId = workflowid;
            browserConditionParam.dataParams.workflowid = workflowid;
        }
    }

    /** 拼接表单内容 */
    getFormWea = () => {
        const {myCreateForm, selectedKey} = this.props;
        const {alldatas, conditioninfo, ispublics, nodestitle, nodedatas} = myCreateForm;
        const {form, workflowid, formtype} = alldatas;
        const {isFormInit} = form;
        let group = [];
        //特殊处理契约锁服务
        isFormInit && conditioninfo && toJS(conditioninfo).map(c => {
            let items = [];
            if(c.type && c.type == "contractoperatingauthority") {//主要是处理操作权限数据
                items.push(this.conoperauth(  form, 1) ) ;
            } else {
                c.items && c.items.map(field => {
                    let col = 1;
                    if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 2;
                    items.push(field.otherParams && field.otherParams.isAssociationST && ispublics ? "" : this.publicFnSetCom(field, form, col, ispublics, workflowid));
                });
            }
            let title = c.title;
            if(c.helpfultip){
                title = <span>{c.title}<WeaHelpfulTip title={c.helpfultip} placement='topLeft' /></span>
            }
            group.push(<WeaSearchGroup needTigger={true} title={title} showGroup={c.defaultshow} items={items}/>)
        });
        return group;
    }

    /**
     * 合同操作权限信息
     */
    conoperauth (form, col) {
        const {myCreateForm} = this.props;
        const {nodestitle, nodedatas, ispublics} = myCreateForm;
        return {
            com: (<WeaFormItem
                label={``}
                labelCol={{span: 0}}
                tipPosition="bottom"
                wrapperCol={{span: 24}}>
                {<NodesTable ispublics={ispublics} columns={nodestitle} datas={nodedatas} store={myCreateForm}/>}
            </WeaFormItem>),
            col: col,
            hide:false,
        }
    }

    /**
     * 添加按钮
     */
    fnAddRightBtn = (dropmenubtn) => {
        const {myCreateForm, selectedKey} = this.props;
        const {alldatas, setShowInterface, addbtns, loading} = myCreateForm
        const {formtype = "getCreateForm"} = alldatas;
        if (formtype == "getEditForm" && selectedKey == 1) {
            dropmenubtn && addbtns && addbtns.map(item => {
                if (item.isrightbtn)
                    dropmenubtn.splice(item.index, 0, {
                        key: item.key,
                        disabled: loading,
                        icon: <i className={item.icon}/>,
                        content: item.name,
                        onClick: item.click.bind(true),
                    })
            })
        }
    }

    /** 开始渲染 */
    render() {
        const {myCreateForm} = this.props;
        const {loading} = myCreateForm
        const dropmenubtn = this.getDropMenbuBtn();
        this.fnAddRightBtn(dropmenubtn);
        return (
            <WeaRightMenu datas={dropmenubtn}>
                <WeaNewScroll ref="scroll" style={{height: "100%", overflow: "auto"}}>
                    <div style={{"padding-right": "25px"}}>
                        {this.getFormWea()}
                    </div>
                </WeaNewScroll>
            </WeaRightMenu>
        )
    }

    /**
     * 获取弹框的操作按钮
     * @returns {*[]}
     */
    getDropMenbuBtn = () => {
        const {myCreateForm} = this.props;
        const {loading} = myCreateForm
        return [
            {
                key: '1',
                disabled: loading,
                icon: <i className="icon-coms-Save-as"/>,
                content: getLabel(86, "保存"),
                onClick: () =>  this.props.fnSaverCreateDatas(),
            }, {
                key: '2',
                disabled: loading,
                icon: <i className="icon-coms-Narrow"/>,
                content: getLabel(201, '取消'),
                onClick: () => this.props.fncanceldialog(),
            },];
    }

    /**
     * 抽取的公有方法用来拼接表单
     * field数据内容
     * form表单
     * col显示colspan
     * ispublic
     * workflowid 流程id
     * */
    publicFnSetCom(field, form, col, ispublic, workflowid) {
        field.domkey[0] == "categoryField1" && (field.hideLabel = true)
        return {
            com: (<WeaFormItem
                label={field.label}
                hideLabel={field.hideLabel}
                labelCol={{span: field.domkey[0] != "wea"? 4 : 0}}
                error={form.getError(field)}
                tipPosition="bottom"
                wrapperCol={{span: field.domkey[0] != "categoryField1"? 20 : 24}}>
                {field.domkey[0] != "categoryField1" ?
                    <WeaSwitch fieldConfig={field} form={form} onChange={this.onChange}/> :
                    <IntegrationForm_Table workflowid={workflowid} ispublic={ispublic}/>}
                {"serverUrl" === field.domkey[0] ? <Button onClick={this.checkServer}>{getLabel(510029, "服务校验")}</Button> : null}
            </WeaFormItem>),
            col: col,
            hide: this.isHide(field, ispublic)
        };
    }

    isHide(field, isPublic) {
        const {selectedKey} = this.props;
        if (0 == selectedKey) {
            return "integratedLoginId" === field.domkey[0] && !isPublic;
        }
        return false;
    }

    /**
     * 服务校验
     */
    checkServer = () => {
        const {myCreateForm} = this.props;
        const {alldatas} = myCreateForm;
        const {form} = alldatas;
        if (!this.props.checkUrl(form, "serverUrl")) {
            return;
        }

        const params = {
            src: "checkServer",
            serverType: form.getFormDatas().serverType.value,
            serverUrl: form.getFormDatas().serverUrl.value,
            accessKey: form.getFormDatas().accessKey.value,
            accessSecret: form.getFormDatas().accessSecret.value
        };
        conLockApi.checkServer(params).then(jo => {
            let message = "";
            if (0 === jo.code) {
                message = getLabel(510119, "服务器版本：{serverVersion}，sdk版本：{sdkVersion}，对比结果：{checkResult}");
                message = message.replace("{serverVersion}", jo.serverVersion).replace("{sdkVersion}", jo.sdkVersion);
                message = message.replace("{checkResult}", jo.checkResult);
            } else {
                message = jo.message;
                if ("" === message) {
                    message = getLabel(510115, "服务校验失败");
                }
            }
            Modal.warning({
                title: getLabel(15172, "系统提示"),
                content: message,
                onOk() {
                    form.showErrors();
                },
                onCancel() {
                    form.showErrors();
                }
            });
        });
    }
}

export default IntegrationForm;